﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using System.Windows.Forms;
using VAdvantage.Model;
using VAdvantage.Utility;
using VAdvantage.Common;
using VAdvantage.Classes;
using VAdvantage.WorkSpace;
using System.Collections.ObjectModel;

namespace VAdvantage.Framework
{
    public partial class Chat : ChildWindow
    {

        #region Private Variables
        //Window No
        private int _windowNo;
        //Attachment
        private MChat _chat;
        // private MChatEntry _entry; 
        //get login info from context class
        VAdvantage.Classes.Context ctx = Utility.Envs.GetContext();
        //change text
        private Boolean _change = false;

        const double SUBTRACTED_WIDTH = 100;
        #endregion

        #region Default constructor
        /// <summary>
        /// Default constructor inherits base class of MainForm
        /// </summary>
        public Chat()
        //: base(false, false, false, false, "Chat")
        {
            //form design
            InitializeComponent();
            LayoutRootChat.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
        }
        #endregion

        #region Parametrised Constructor
        /// <summary>
        /// Parametrised Constructor.
        /// loads Chat, if ID <> 0
        /// </summary>
        /// <param name="windowNo">window no</param>
        /// <param name="CM_Chat_ID">chat</param>
        /// <param name="AD_Table_ID">table</param>
        /// <param name="Record_ID">record key</param>
        /// <param name="description">description</param>
        /// <param name="trxName">transaction</param>
        public Chat(int windowNo, int CM_Chat_ID, int AD_Table_ID, int Record_ID, String description, String trxName)
        // : base(false, false, false, false, "Chat")
        {
            //set current window
            _windowNo = windowNo;
            //from design
            InitializeComponent();
           // this.Cursor = Cursors.Wait;
            SetBusy(true);
            double width = this.Width;
            LayoutRootChat.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
            EventHander();
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                //	when chatId is zero
                if (CM_Chat_ID == 0)
                {
                    //set chat from MChat class first time
                    _chat = new MChat(ctx, AD_Table_ID, Record_ID, description, trxName);
                    // _chat = new MChat(ctx, 0, trxName);
                }
                else
                {
                    //set chat from MChat class includeing previous chat
                    _chat = new MChat(ctx, CM_Chat_ID, trxName);
                }
                // String text = _chat.GetHistory(MChat.CONFIDENTIALTYPE_Internal);
                ObservableCollection<LatestSubscribedRecordChat> subsribedChat = new ObservableCollection<LatestSubscribedRecordChat>();
                subsribedChat = _chat.GetHistory(MChat.CONFIDENTIALTYPE_Internal,width- SUBTRACTED_WIDTH);
                //Call Load Chat function 
                Deployment.Current.Dispatcher.BeginInvoke(() => ShowText(subsribedChat));
                //Deployment.Current.Dispatcher.BeginInvoke(LoadChat);
            });
            //Call Load Chat function 
            //LoadChat();
            //set focus on text box
            //rtxtEnter.Focus();
        }
        #endregion

        public void EventHander()
        {
            this.KeyDown += new KeyEventHandler(Chat_KeyDown);
        }

        void Chat_KeyDown(object sender, KeyEventArgs e)
        {
            //throw new NotImplementedException();
            if (e.Key == Key.Enter)
            {
                Ok();
            }
            if (e.Key == Key.Escape)
            {
                this.DialogResult = false;
            }
        }


        public void SetBusy(bool value)
        {

            this.IsEnabled = !value;
            busyWindow.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            txtBusy.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }

        #region Load Chat
        /// <summary>
        /// Load Chat
        /// </summary>
        private void LoadChat()
        {
            double width =  this.Width  ;
            //get chat text from database
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                //   String text = _chat.GetHistory(MChat.CONFIDENTIALTYPE_Internal);
                ObservableCollection<LatestSubscribedRecordChat> subsribedChat = new ObservableCollection<LatestSubscribedRecordChat>();
                subsribedChat = _chat.GetHistory(MChat.CONFIDENTIALTYPE_Internal,width- SUBTRACTED_WIDTH);
                //show text in browser
                //webBrowser1.DocumentText = text;
                //Deployment.Current.Dispatcher.BeginInvoke(() => rtxtBrowser.Selection.Text = text);
                Deployment.Current.Dispatcher.BeginInvoke(() => ShowText(subsribedChat));
                //rtxtEnter.SelectAll();
                //rtxtBrowser.Selection.Text = text;
                //rtxtEnter.Focus();
            });
        }

        private void ShowText(ObservableCollection<LatestSubscribedRecordChat> subsribedChat)
        {
            SetBusy(false);
            //this.Cursor = Cursors.Arrow;
            lstChatRecords.ItemsSource = subsribedChat;
            rtxtEnter.Focus();
            // StringBuilder str = new StringBuilder();
            // str.Append(text);
            // str.Replace("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>", "");
            // str.Replace("<html xmlns='http://www.w3.org/1999/xhtml'>", "");
            // str.Replace("<head>", "");
            // str.Replace("<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />", "");
            // str.Replace("<title>Untitled Document</title>", "");
            // str.Replace("<style type='text/css'>", "");
            // str.Replace("<!--body {margin-left: 0px;margin-top: 0px;margin-right: 0px;margin-bottom: 0px;font-family:Arial;font-size:12px;}.grey{color:#969292;}.grey-1{font-size:10px;color:#969292;}-->", "");
            // str.Replace("</style>", "");
            // str.Replace("</head>", "");
            // str.Replace("<body>", "");
            // str.Replace("&nbsp;", "");
            // str.Replace("</body>", "");
            // str.Replace("</html>", "");

            // rtxtEnter.SelectAll();
            //// txtHtml.Html = str.ToString();
            // rtxtEnter.Focus();


        }
        #endregion

        #region Ok Button Click
        /// <summary>
        /// Action Performed
        /// </summary>
        /// <param name="sender">button click</param>
        /// <param name="e">event</param>
        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            Ok();
        }

        public void Ok()
        {
            SetBusy(true);
           // this.Cursor = Cursors.Wait;
            btnOK.IsEnabled = false;
            rtxtEnter.SelectAll();//to get all text fromrich text box

            //if (rtxtEnter.Text.Trim() != "" && rtxtEnter.Text.Trim() != null)
            if (rtxtEnter.Selection.Text.Trim() != "" && rtxtEnter.Selection.Text.Trim() != null)
            {
                //String data = newText.getText();
                string data = rtxtEnter.Selection.Text;
                if (data != null && data.Length > 0)
                {
                    double width = this.Width;
                    System.Threading.ThreadPool.QueueUserWorkItem(delegate
                    {
                        // log.config(data);
                        if (_chat.Get_ID() == 0)
                        {
                            _chat.Save();
                        }
                        MChatEntry entry = new MChatEntry(_chat, data);
                        entry.Save();
                        //LoadChat();
                        //   String text = _chat.GetHistory(MChat.CONFIDENTIALTYPE_Internal);
                        ////ObservableCollection<LatestSubscribedRecordChat> subsribedChat = new ObservableCollection<LatestSubscribedRecordChat>();
                        ////subsribedChat = _chat.GetHistory(MChat.CONFIDENTIALTYPE_Internal,width-SUBTRACTED_WIDTH);
                        //Deployment.Current.Dispatcher.BeginInvoke(() => CloseDialoge(subsribedChat));
                        Deployment.Current.Dispatcher.BeginInvoke(delegate
                        {
                            this.DialogResult = false;
                        });
                    });
                }
                this.rtxtEnter.Selection.Text = "";
            }
            else
            {
                ShowMessage.Info("PleaseEnterText", null, "", "");
              //  Envs.SetBusyIndicator(false);
                btnOK.IsEnabled = true;
                SetBusy(false);
               // this.Cursor = Cursors.Arrow;
                rtxtEnter.Focus();
            }
        }


        public void CloseDialoge(ObservableCollection<LatestSubscribedRecordChat> subsribedChat)
        {
            ShowText(subsribedChat);
            SetBusy(false);
            //this.Cursor = Cursors.Arrow;
            btnOK.IsEnabled = true;
            this.DialogResult = false;
        }
        #endregion

        #region Cancel button Click
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            //close current window
            //this.Close();
            this.DialogResult = false;
        }
        #endregion

        #region Form Load Event
        private void Chat_Load(object sender, RoutedEventArgs e)
        {
            //set text box focus
            rtxtEnter.Focus();
        }
        #endregion

        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }


    }
}
